package com.fingard.dsp.bank.directbank.crbc01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directbank.bankInterface.IStatement;
import com.fingard.dsp.bank.reqrespobj.statement.ReqQryStatement;
import com.fingard.dsp.bank.reqrespobj.statement.RetAtsStatement;
import com.fingard.dsp.bank.reqrespobj.statement.TransState;
import com.fingard.dsp.bank.reqrespobj.statement.detail.RetAtsStatementDetail;
import com.fingard.io.FileHelper;
import com.fingard.net.FtpPortClient;
import com.fingard.net.FtpReceiver;
import com.fingard.net.SftpPortClient;
import com.fingard.text.StringHelper;

import java.io.BufferedReader;
import java.io.File;
import java.io.StringReader;

public class CRBC01Statement extends CRBC01Base implements IStatement
{
    @Override
    public RetAtsStatement d_Qry_Statement(ReqQryStatement p_reqQrySttm) throws Exception {
        RetAtsStatement retAts = new RetAtsStatement(p_reqQrySttm);
        retAts.writeStart();

        String[] tmpNoCardRespHeader = getNoCardStatement(p_reqQrySttm, retAts);
        String tmpNoCardTotalNum = retAts.totalNum;
        if ("".equals(tmpNoCardTotalNum)) {
            tmpNoCardTotalNum = "0";
        }
        String[] tmpTransRespHeader = getTransStatement(p_reqQrySttm, retAts);
        String tmpTransTotalNum = retAts.totalNum;
        if ("".equals(tmpTransTotalNum)) {
            tmpTransTotalNum = "0";
        }
        if ("-1".equals(tmpTransRespHeader[0]) && "-1".equals(tmpNoCardRespHeader[0])) {
            retAts.writeRespCode("-1");
            retAts.writeRespInfo("传统收单明细对账单获取失败,原因:" + tmpTransRespHeader[1] + ",无卡收单明细对账单获取失败,原因:" + tmpNoCardRespHeader[1]);
        } else {
            if (retAts.getWrittenRdCount() == 0) {
                retAts.writeRespCode("0");
                String respInfo = tmpTransRespHeader[1];
                if (StringHelper.isNullOrEmpty(respInfo)) {
                    respInfo = "交易为空";
                }
                retAts.writeRespInfo(respInfo);
            }
            retAts.isWritedTotalNum(String.valueOf(Integer.parseInt(tmpTransTotalNum) + Integer.parseInt(tmpNoCardTotalNum)));
        }

        retAts.writeEnd();
        return retAts;
    }

    /**
     * 无卡收单明细文件
     *
     * @param p_reqQrySttm
     * @param retAts
     * @return
     * @throws Exception
     */

    private String[] getNoCardStatement(ReqQryStatement p_reqQrySttm, RetAtsStatement retAts) throws Exception {
        String[] respHeader = new String[]{"", ""};

        String tmpRespCode = "";
        String tmpRespInfo = "";

        retAts.totalNum = "0";
        int totalNum = 0;

        try {
            FtpSet ftpSet = bankFront.getFtpSet("noCardPos");
            WriteBankLogLn2("华润银行无卡收单POS对账单FTP服务器地址:" + ftpSet.serverIP + ":" + ftpSet.port);

            /**
             * 无卡收单明细文件命名规则：8位日期_01_AC_NCOMTRX_13(23)
             * 20191009_01_AC_NCOMTRX_13
             **/
            StringBuilder sbFileContent = new StringBuilder();
            String downFileName = p_reqQrySttm.busDate + "_01_AC_NCOMTRX_13";
            WriteBankLogLn2("华润银行无卡收单POS对账单所在服务器路径:" + ftpSet.downDir + "/" + downFileName);

            String localFilePath = createTempFileDirectory() + File.separator + downFileName;
            WriteBankLogLn2("华润银行无卡收单POS对账单保存本地路径:" + localFilePath);

            FtpReceiver ftpReceiver = null;
            String posRecRequestType = getBankConfig().getValueAsString("posRecRequestType");
            WriteBankLogLn("华润银行无卡收单POS对账单获取类型" + posRecRequestType);
            if ("ftp".equals(posRecRequestType.toLowerCase())) {
                FtpPortClient ftpPortClient = new FtpPortClient(ftpSet);
                ftpReceiver = ftpPortClient.downloadFile(downFileName, localFilePath);
            } else if ("sftp".equals(posRecRequestType.toLowerCase())) {
                SftpPortClient sftpPortClient = new SftpPortClient(ftpSet);
                String sftpFilePath = StringHelper.trimEnd(ftpSet.downDir, "/") + "/" + downFileName;
                WriteBankLogLn2("待下载SFTP服务器文件路径:\r\n" + sftpFilePath);
                ftpReceiver = sftpPortClient.downloadFile("",sftpFilePath, localFilePath);
            }
            if (ftpReceiver.isCompleted) {
                if (sbFileContent.length() > 0) {
                    sbFileContent.append("\n");
                }
                sbFileContent.append(FileHelper.readFileText(localFilePath, getCharset("UTF-8", "pos")));
            } else {
                tmpRespCode = "-1";
                tmpRespInfo = "华润银行无卡收单POS对账单下载失败,原因:\r\n" + ftpReceiver.connMsg;
            }
//            sbFileContent.append(FileHelper.readFileText("C:\\Users\\dell\\Downloads\\DSPJAVA-11622\\20191009_01_AC_NCOMTRX_13", getCharset("UTF-8", "pos")));

            if (StringHelper.hasAnyChar(sbFileContent.toString())) {
                String tmpStrRet = sbFileContent.toString();
                WriteBankLogLn2("华润银行无卡收单POS对账单响应数据:\r\n" + tmpStrRet);

                tmpRespCode = "0";
                /**
                 * 文件头
                 * N01;50
                 * 交易类型;交易流水号;交易金额;业务种类;清算日期;原交易流水号;原支付交易金额;订单号;发送机构标识;
                 * 付款方账户所属机构标识;付款方账户类型;付款方账户;渠道方机构标识;签约协议号;收款方账户所属机构标识;
                 * 收款方账户类型;收款方账户;保留域1;保留域2;产品类型;产品辅助信息;商户编码;商户类别;二级商户编码;
                 * 二级商户类别;交易终端类型;网络服务费;品牌费;应付业务参与价;应收业务参与价;商户名称;二级商户名称;
                 * 发起/接收方保留域;清算信息;交易状态;交易日期时间;业务功能;原交易类型;原业务功能;商户分期实际贴息费率;
                 * 分期期数;业务推广费;商户分期贴息;网关渠道标识;付款方名称;付款方开户行支付系统行号;付款方开户行支付系统行名称;
                 * 收款方名称;收款方开户行支付系统行号;收款方开户行支付系统行名称
                 * 1101;1008CoNCUZ2YfEH7;156000000008000;120003;20191009;1008ClN95YCHP3St;156000000008000;UPOrderTest000000001;
                 * 04379200;04379200;;;0104379200;;04379200;01;6223635808001597674;;;;;MrchntNo0000001;5411;abc123456789123;;
                 * 07;00000000000;00000000000;156000000000004;156000000000000;中国银联无卡快捷支付业务测试商户信息测试;
                 * 中国银联无卡快捷支付业务 2 级商户信息测试;;1113;3;20191009102753;;;;;;;;;;;;;;
                 */
                StringReader strReader = new StringReader(tmpStrRet);
                BufferedReader tmpReader = new BufferedReader(strReader);

                boolean isContinue = false;
                while(true) {
                    String eachline = tmpReader.readLine();
                    if(eachline == null){
                        break;
                    }
                    if ("".equals(eachline)) {
                        continue;
                    }
                    String[] detailNodes = eachline.split(";");
                    if (detailNodes.length > 2) {
                        if (p_reqQrySttm.actNum.equals(detailNodes[16].trim())) {
                            totalNum++;
                            isContinue = true;
                            RetAtsStatementDetail tmpRetDetail = new RetAtsStatementDetail();
                            if (StringHelper.hasAnyChar(detailNodes[1])) {
                                tmpRetDetail.askNumber = detailNodes[1].trim();
                            }
                            float fee = 0;
                            if (StringHelper.hasAnyChar(detailNodes[24])) {
                                if ("D".equals(detailNodes[24].substring(0,1))) {
                                    tmpRetDetail.cdFlag = "27";
                                    fee = Float.parseFloat(StringHelper.amountDivide100(detailNodes[24].substring(1)));//网络服务费
                                } else {
                                    tmpRetDetail.cdFlag = "22";
                                    fee = Float.parseFloat(StringHelper.amountDivide100(detailNodes[24]));
                                }
                            } else if (StringHelper.hasAnyChar(detailNodes[25])) {
                                if ("D".equals(detailNodes[25].substring(0,1))) {
                                    tmpRetDetail.cdFlag = "27";
                                    fee += Float.parseFloat(StringHelper.amountDivide100(detailNodes[25].substring(1)));//品牌费
                                } else {
                                    tmpRetDetail.cdFlag = "22";
                                    fee += Float.parseFloat(StringHelper.amountDivide100(detailNodes[25]));//品牌费
                                }
                            }
                            if (StringHelper.hasAnyChar(detailNodes[26])) {
                                fee += Float.parseFloat(StringHelper.amountDivide100(detailNodes[26].substring(3)));//应付业务参与价
                            }
                            if (StringHelper.hasAnyChar(detailNodes[27])) {
                                fee += Float.parseFloat(StringHelper.amountDivide100(detailNodes[27].substring(3)));//应收业务参与价
                            }
                            tmpRetDetail.fee = String.valueOf(fee);
                            if (StringHelper.hasAnyChar(detailNodes[2])) {
                                tmpRetDetail.amount = StringHelper.amountDivide100(detailNodes[2].trim());
                            }
                            tmpRetDetail.busTime = Format.DateTime14Format.format(Format.Date8Format.parse(detailNodes[4]));
                            if (StringHelper.hasAnyChar(detailNodes[11])) {
                                tmpRetDetail.oppAct = detailNodes[11].trim();
                            }
                            tmpRetDetail.transState = TransState.Success;
                            retAts.writeRetDetail(tmpRetDetail);
                        }
                    }
                }
                if (!isContinue) {
                    tmpRespCode = "0";
                    tmpRespInfo = "没有符合条件的记录!";
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            tmpRespCode = "-1";
            tmpRespInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }

        retAts.totalNum = String.valueOf(totalNum);

        respHeader[0] = tmpRespCode;
        respHeader[1] = tmpRespInfo;

        return respHeader;
    }

    /**
     * 传统收单明细文件
     *
     * @param p_reqQrySttm
     * @param retAts
     * @return
     * @throws Exception
     */
    private String[] getTransStatement(ReqQryStatement p_reqQrySttm, RetAtsStatement retAts) throws Exception {
        String[] respHeader = new String[]{"", ""};

        String tmpRespCode = "";
        String tmpRespInfo = "";

        retAts.totalNum = "0";
        int totalNum = 0;

        try {
            FtpSet ftpSet = bankFront.getFtpSet("transPos");
            WriteBankLogLn2("华润银行传统收单POS对账单FTP服务器地址:" + ftpSet.serverIP + ":" + ftpSet.port);

            /**
             * 传统收单明细文件命名规则：IND+6位日期+32+ACOMA
             * IND19090432ACOMA
             */
            StringBuilder sbFileContent = new StringBuilder();
            String downFileName = "IND" + p_reqQrySttm.busDate.substring(2) + "32ACOMA";
            WriteBankLogLn2("华润银行传统收单POS对账单所在服务器路径:" + ftpSet.downDir + "/" + downFileName);

            String localFilePath = createTempFileDirectory() + File.separator + downFileName;
            WriteBankLogLn2("华润银行传统收单POS对账单保存本地路径:" + localFilePath);

            FtpReceiver ftpReceiver = null;
            String posRecRequestType = getBankConfig().getValueAsString("posRecRequestType");
            WriteBankLogLn("华润银行传统收单POS对账单获取类型" + posRecRequestType);
            if ("ftp".equals(posRecRequestType.toLowerCase())) {
                FtpPortClient ftpPortClient = new FtpPortClient(ftpSet);
                ftpReceiver = ftpPortClient.downloadFile(downFileName, localFilePath);
            } else if ("sftp".equals(posRecRequestType.toLowerCase())) {
                SftpPortClient sftpPortClient = new SftpPortClient(ftpSet);
                String sftpFilePath = StringHelper.trimEnd(ftpSet.downDir, "/") + "/" + downFileName;
                WriteBankLogLn2("待下载SFTP服务器文件路径:\r\n" + sftpFilePath);
                ftpReceiver = sftpPortClient.downloadFile("",sftpFilePath, localFilePath);
            }
            if (ftpReceiver.isCompleted) {
                if (sbFileContent.length() > 0) {
                    sbFileContent.append("\n");
                }
                sbFileContent.append(FileHelper.readFileText(localFilePath, getCharset("UTF-8", "pos")));
            } else {
                tmpRespCode = "-1";
                tmpRespInfo = "华润银行传统收单POS对账单下载失败,原因:\r\n" + ftpReceiver.connMsg;
            }
//            sbFileContent.append(FileHelper.readFileText("C:\\Users\\dell\\Downloads\\DSPJAVA-11622\\IND19090432ACOMA", getCharset("UTF-8", "pos")));
            if (StringHelper.hasAnyChar(sbFileContent.toString())) {
                String tmpStrRet = sbFileContent.toString();
                WriteBankLogLn2("华润银行传统收单POS对账单响应数据:\r\n" + tmpStrRet);

                tmpRespCode = "0";
                StringReader strReader = new StringReader(tmpStrRet);
                BufferedReader tmpReader = new BufferedReader(strReader);

                boolean isContinue = false;
                while(true) {
                    String eachline = tmpReader.readLine();
                    if(eachline == null){
                        break;
                    }
                    if ("".equals(eachline)) {
                        continue;
                    }
                    if (p_reqQrySttm.actNum.equals(eachline.substring(127, 143).trim())) {
                        totalNum++;
                        isContinue = true;
                        RetAtsStatementDetail tmpRetDetail = new RetAtsStatementDetail();
                        String askNumber = eachline.substring(42,62).trim()+"_"+eachline.substring(31,42).trim()+"_"+StringHelper.amountDivide100(eachline.substring(62,75).trim());
                        tmpRetDetail.askNumber = askNumber;
                        if ("D".equals(eachline.substring(218,219))) {
                            tmpRetDetail.cdFlag = "27";
                        } else {
                            tmpRetDetail.cdFlag = "22";
                        }
                        float fee = 0;
                        if (StringHelper.hasAnyChar(eachline.substring(192,205))) {
                            fee = Float.parseFloat(StringHelper.amountDivide100(eachline.substring(192,205).trim()));//受理方应收交换费
                        }
                        if (StringHelper.hasAnyChar(eachline.substring(205,218))) {
                            fee += Float.parseFloat(StringHelper.amountDivide100(eachline.substring(205,218).trim()));//受理方应付交换费
                        }
                        if (StringHelper.hasAnyChar(eachline.substring(218,231))) {
                            fee += Float.parseFloat(StringHelper.amountDivide100(eachline.substring(219,231).trim()));//转接清算费
                        }

                        tmpRetDetail.fee = String.valueOf(fee);
                        if (StringHelper.hasAnyChar(eachline.substring(62,75))) {
                            tmpRetDetail.amount = StringHelper.amountDivide100(eachline.substring(62,75).trim());
                        }
                        tmpRetDetail.busTime = Format.DateTime14Format.format(Format.Date10Format4.parse(eachline.substring(31,42).trim()));
                        tmpRetDetail.oppAct = eachline.substring(42,62).trim();
                        tmpRetDetail.transState = TransState.Success;
                        retAts.writeRetDetail(tmpRetDetail);
                    }
                }
                if (!isContinue) {
                    tmpRespCode = "0";
                    tmpRespInfo = "没有符合条件的记录!";
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            tmpRespCode = "-1";
            tmpRespInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }

        retAts.totalNum = String.valueOf(totalNum);

        respHeader[0] = tmpRespCode;
        respHeader[1] = tmpRespInfo;

        return respHeader;
    }

}
